#!/bin/bash

# ArXiv Subscription Platform - Simple Deploy Script
# Minimal deployment without database setup for testing

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
ENVIRONMENT=${1:-development}
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

print_status "ArXiv Subscription Platform - Simple Deploy"
print_status "Environment: $ENVIRONMENT"
print_status "Project root: $PROJECT_ROOT"

# Check Python version
print_status "Checking Python version..."
if ! command -v python3 &> /dev/null; then
    print_error "Python 3 is required but not installed"
    exit 1
fi

python_version=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
if python3 -c "import sys; exit(0 if sys.version_info >= (3, 8) else 1)"; then
    print_success "Python version $python_version is compatible (3.8+ required)"
else
    print_error "Python 3.8+ is required, found $python_version"
    exit 1
fi

# Setup Python virtual environment
print_status "Setting up Python virtual environment..."
if [ ! -d "venv" ]; then
    python3 -m venv venv
fi
source venv/bin/activate

# Install Python dependencies
print_status "Installing Python dependencies..."
pip install --break-system-packages --upgrade pip
pip install --break-system-packages -r requirements_minimal.txt

print_success "Dependencies installed successfully"

# Create minimal config for testing
print_status "Creating test configuration..."
cat > .env << EOF
# Test configuration
DATABASE_URL=sqlite:///./test.db
REDIS_URL=redis://localhost:6379
SECRET_KEY=test-secret-key-please-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
SMTP_SERVER=localhost
SMTP_PORT=587
SMTP_USERNAME=test@example.com
SMTP_PASSWORD=test-password
EMAIL_FROM=test@example.com
ENVIRONMENT=$ENVIRONMENT
EOF

# Create a simple test script
print_status "Creating test server script..."
cat > run_test_server.py << 'EOF'
#!/usr/bin/env python3
"""
Simple test server for ArXiv Subscription Platform
Runs without database dependencies for testing
"""

import os
import sys
from pathlib import Path

# Add backend to Python path
backend_path = Path(__file__).parent / "backend"
sys.path.insert(0, str(backend_path))

try:
    import uvicorn
    from fastapi import FastAPI
    from fastapi.responses import JSONResponse
    
    app = FastAPI(title="ArXiv Subscription Platform - Test Mode")
    
    @app.get("/")
    async def root():
        return {"message": "ArXiv Subscription Platform - Test Mode", "status": "running"}
    
    @app.get("/health")
    async def health():
        return {"status": "healthy", "environment": os.getenv("ENVIRONMENT", "test")}
    
    @app.get("/api/test")
    async def test_api():
        return {"message": "API is working", "python_version": sys.version}
    
    if __name__ == "__main__":
        print("Starting ArXiv Subscription Platform test server...")
        print("Access the API at: http://localhost:8000")
        print("API docs at: http://localhost:8000/docs")
        print("Health check: http://localhost:8000/health")
        uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

except ImportError as e:
    print(f"Error importing dependencies: {e}")
    print("Please ensure all dependencies are installed")
    sys.exit(1)
EOF

chmod +x run_test_server.py

print_success "Test environment setup completed!"
print_status ""
print_status "🚀 Ready to test!"
print_status ""
print_status "To start the test server:"
print_status "  source venv/bin/activate"
print_status "  python run_test_server.py"
print_status ""
print_status "API will be available at:"
print_status "  - Main: http://localhost:8000"
print_status "  - Docs: http://localhost:8000/docs"  
print_status "  - Health: http://localhost:8000/health"
print_status ""
print_warning "Note: This is a minimal test setup without database."
print_warning "For full deployment, ensure PostgreSQL and Redis are installed."